package com.crazymakercircle.designmodel.masterworker;

import com.crazymakercircle.util.Print;
import lombok.Data;

import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 8.2.1 Master-Worker 模式的参考实现
 * 单独抽取的结果类
 */
@Data
public class IntegerResult {
    //任务处理结果集
    private Map<String, Integer> resultMap;

    //保持最终的和
    private AtomicLong sum;

    public IntegerResult(Map<String, Integer> resultMap, AtomicLong sum) {
        this.resultMap = resultMap;
        this.sum = sum;
    }

    //结果处理的回调函数
    public void resultCallBack(Object o) {
        Task<Integer> task = (Task<Integer>) o;
        String taskName = "Worker:" + task.getWorkerId() + "-" + "Task:" + task.getId();
//        Print.tco(taskName + ":" + task.getResult());
        Integer result = task.getResult();
        resultMap.put(taskName, result);

        sum.getAndAdd((Integer) result);
    }

    // 获取最终的结果
    public void printResult() {
        Print.tco("----------sum is :" + sum.get());
        for (Map.Entry<String, Integer> entry : resultMap.entrySet()) {
            String taskName = entry.getKey();
            Print.fo(taskName + ":" + entry.getValue());
        }

    }
}
